package com.mach.platform.utils.springdata;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Map.Entry;

/**
 * @author Anonymous
 * @Name
 * @Description: SearchFilter处理参数
 * @date 2018/04/21   11:24
 */
public class SearchFilter {

	public enum Operator {
		/**
		 * 等于字段
		 */
		EQ, /**
		 * 模糊搜索
		 */
		LIKE, /**
		 * 大于
		 */
		GT, /**
		 * 小于
		 */
		LT, /**
		 * 大于等于
		 */
		GTE, /**
		 * 小于等于
		 */
		LTE, /**
		 * 多个字段属性 like 一个值
		 * realName_mobile_userName_education_major_nativePlace_plike
		 */
		PLIKE, VLIKE, NN, NIN
	}

	public String   fieldName;
	public Object   value;
	public Operator operator;

	public SearchFilter (String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	/**
	 * searchParams中key的格式为OPERATOR_FIELDNAME
	 */
	public static Map<String, SearchFilter> parse (Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = Maps.newHashMap();

		for (Entry<String, Object> entry : searchParams.entrySet()) {
			// 过滤掉空值
			String key = entry.getKey();
			Object value = entry.getValue();
			if ("".equals(value) || value == null) {
				continue;
			}
			//过滤掉分页的参数
			if (( "size" ).equals(key) || ( "page" ).equals(key)) {
				continue;
			}
			// 拆分operator与filedAttribute
			String[] names = StringUtils.split(key, "_");
			if (names.length < 2) {
				throw new IllegalArgumentException(key + " is not a valid search filter name");
			}

			String filedName = key.substring(0, key.lastIndexOf("_"));
			Operator operator = Operator.valueOf(names[names.length - 1].toUpperCase());

			// 创建searchFilter
			SearchFilter filter = new SearchFilter(filedName, operator, value);
			filters.put(key, filter);
		}

		return filters;
	}
}
